/**
 * @(#)MonitorOnlineUserAndSimulatorTask.java 2017年02月10日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */

package org.jsbd.boss.task;

import org.jsbd.boss.monitor.service.MonitorSimulatorNumServiceImpl;
import org.jsbd.boss.service.IChannelApkInfoService;
import org.jsbd.boss.service.IEmailSendService;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.channel.ChannelApkConfig;
import org.jsbd.boss.monitor.service.MonitorBaseService;
import org.jsbd.boss.monitor.service.MonitorDownLoadServiceImpl;
import org.jsbd.boss.monitor.service.MonitorMobileServiceImpl;
import org.jsbd.boss.monitor.service.MonitorSimulatorActionServiceImpl;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.DateUtil;
import org.jsbd.boss.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 数据监控
 * @author Administrator
 *
 */
public class MonitorOnlineTask extends BaseTask {

	public static final Logger LOGGER = LoggerFactory.getLogger(MonitorOnlineTask.class);

	/**
	 * 数据获取间隔，单位分钟
	 */
    protected static final int INTERVAL_TIME=30;
    /**
     * 1小时（毫秒）
     */
	protected static final int ONE_HOUR_TIME=60*60*1000;
	/**
	 * 30分钟（毫秒）
	 */
	protected static final int THIRTY_MINUTE_TIME=30*60*1000;
	
	@Autowired
	private MonitorSimulatorNumServiceImpl monitorSimulatorNumService;
	@Autowired
	private MonitorSimulatorActionServiceImpl monitorSimulatorActionService;
	@Autowired
	private MonitorMobileServiceImpl monitorMobileService;
	@Autowired
	private MonitorDownLoadServiceImpl monitorDownLoadService;
	@Autowired
	private IChannelApkInfoService channelApkInfoService;
	@Autowired
	private IEmailSendService emailSendService;
	@Autowired
	private RedisClient<String,Date> redisClient;
	
	private List<MonitorBaseService> serviceList=new ArrayList<MonitorBaseService>();
	
	public void init() {
		super.setOpenFlag(PropertiesUtil.getValue("monitor_online_open_flag", "off"));
		super.setCycleTime(PropertiesUtil.getInt("monitor_cycle_time", 15000));
		super.init();
		
		serviceList.add(monitorSimulatorNumService);
		serviceList.add(monitorMobileService);
//		serviceList.add(monitorDownLoadService);
		serviceList.add(monitorSimulatorActionService);
	}

	@Override
	public void run() {
		while (true) {
			try {
				LOGGER.info("START 监控");
				
				long startTime=System.currentTimeMillis();
				
				Map<String,Object> conditionMap=getConditionMap();
				if(conditionMap==null){
					LOGGER.debug("还未到执行时间");
					continue;
				}
				
				List<ChannelApkConfig> apkList = channelApkInfoService.selectApkConfigsAndSimulator();
				if(apkList==null||apkList.isEmpty()){
					LOGGER.warn("当前没有可用的apk配置");
					continue;
				}
				
				Map<String,ChannelApkConfig> apkConfigMap=new HashMap<String,ChannelApkConfig>();
				for(ChannelApkConfig config:apkList){
					apkConfigMap.put(config.getMark(), config);
				}
				
				StringBuffer buffer=new StringBuffer();
				List<String> attachmentList=new ArrayList<String>();
				
				for(MonitorBaseService serivce:serviceList){
					Map<String,String> resultMap=serivce.getMonitorContent(apkList, apkConfigMap,conditionMap);
					
					String sheetName=resultMap.get("sheetName");
					if(StringUtils.isNotBlank(sheetName)){
						buffer.append("<div style=\"font-size:x-large;text-align:center\"><b>"+sheetName+"</b><div><br>");
					}
					
					String content=resultMap.get("content");
					if(StringUtils.isNotBlank(content)){
						buffer.append(content).append("<br><hr><br>");
					}
					
					String attachFile=resultMap.get("attachFile");
					if(StringUtils.isNotBlank(attachFile)){
						attachmentList.add(attachFile);
					}
				}
				
				if(StringUtils.isBlank(buffer.toString())){
					buffer.append("获取不到数据，如果邮件一直这样，请联系技术人员");
				}
				
				LOGGER.info("START SEND EMAIL");
				//emailSendService.sendEmailToSysAccount("监控", buffer.toString(), attachmentList.toArray(new String[0]));
				emailSendService.sendEmailToSysAccountGroup("监控", buffer.toString(), attachmentList.toArray(new String[0]), "Y1");
				
				long costTime=System.currentTimeMillis()-startTime;
				if(costTime>30000){
					LOGGER.warn("MonitorOnlineTask cost time is [{}]",costTime);
				}else{
					LOGGER.debug("MonitorOnlineTask cost time is [{}]",costTime);
				}
				
			} catch (Exception e) {
				LOGGER.error("", e);
			} finally {
				try {
					Thread.sleep(super.getCycleTime());
				} catch (InterruptedException e) {
					LOGGER.error("", e);
				}
			}
		}

	}
	
    public Map<String,Object> getConditionMap(){
		
		long currentTime=System.currentTimeMillis();
		Date startTime=(Date)redisClient.get(CacheKey.MONITOR_STARTTIME_KEY);
		//如果开始时间小于半个小时，则不执行
		if(startTime!=null&&startTime.getTime()>currentTime-THIRTY_MINUTE_TIME){
			return null;
		}
		
		//如果开始时间距离现在大于了1个小时，则重新赋值为之前半小时
		if(startTime==null||(startTime.getTime()>currentTime-ONE_HOUR_TIME)){
			startTime=getPreMinitusTime(new Date());
		}
		
		Date endTime=new Date();
		
		Map<String,Object> conditionMap=new HashMap<String,Object>();
		conditionMap.put("currentDate", DateUtil.getCurrentDateStr());
		conditionMap.put("startTime", startTime);
	    conditionMap.put("endTime", endTime);
		
	    redisClient.put(CacheKey.MONITOR_STARTTIME_KEY,endTime);
	    return conditionMap;
	}
	
	public Date getPreMinitusTime(Date time){
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(time);
		calendar.add(Calendar.MINUTE,-INTERVAL_TIME);
		return calendar.getTime();
	}
	
}
